import { showDialog ,showSuccessToast,showFailToast,showNotify } from 'vant';
import 'vant/lib/toast/style'
import axios, {
    type InternalAxiosRequestConfig,
    type AxiosResponse,
  } from "axios";
  import qs from "qs";
  import router from '@/router'; 
  import { getToken, getLanguage } from "@/utils/auth";
  import { useUserStore } from "@/stores";
  // 创建 axios 实例
  const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" },
    paramsSerializer: (params) => {
      return qs.stringify(params);
    },
  });
  
  // 请求拦截器
  service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      // 登录认证token
      const accessToken = useUserStore().token || getToken();
      if (accessToken) {
        config.headers.Authorization = `Bearer ${accessToken}`;
      }
      // 语言
      const language = getLanguage();
      if (language) {
        config.headers.language = language;
      }
      return config;
    },
    (error: any) => {
      return Promise.reject(error);
    }
  );
  
  // 响应拦截器
  service.interceptors.response.use(
    (response: AxiosResponse) => {
      // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
      if (
        response.config.responseType === "blob" ||
        response.config.responseType === "arraybuffer"
      ) {
        return response;
      }
      // const { code, data, msg } = response.data;
      if (response.data.code === 200) {
        return response.data;
      } else if ( response.data.code === 405 || response.data.code === 406 ) {

        const userStore = useUserStore();
        userStore.logout();
        router.replace('/login'); // 退出后跳转登录页
        showFailToast('请重新登录');
        // showDialog({
        //   message: '生命远不止连轴转和忙到极限，人类的体验远比这辽阔、丰富得多。',
        // }).then(() => {
        //   // on close
        // });
      } else {
        showFailToast(response.data.msg || "system error!");
      }
  
      // showFailToast(msg || "system error!");
      return Promise.reject(new Error(response.data.msg || "Error"));
    },
    (error: any) => {
      // 异常处理 非 2xx 状态码 会进入这里
      if (error.response.data) {
        // const { code, msg } = error.response.data;
  
        if (
          error.response.code === 405 ||
          error.response.code === 406
        ) {
          // 新增网络错误处理
          const userStore = useUserStore();
          userStore.logout();
          router.replace('/login');
          showNotify({ message: '登录已过期，请重新登录' });
          // useUserStoreHook()
          //   .clearUserSession()
          //   .then(() => {
          //     location.reload();
          //   });
        } else {
          showFailToast(error.response.msg || "system error!");
        }
      }
      return Promise.reject(error.message);
    }
  );
  
  export default service;
  